import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import qs from 'qs'

const base_url = `${window.axiosConfig.base_url}`
export function getApiUrl() {
  let uri;
  if (!window.location.origin) {
    uri = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port : '')
  } else {
    uri = window.location.origin + '/'
  }

  //测试
  if (uri.indexOf('localhost') > 0 || uri.indexOf('127.0.0.1') > 0)  //本地环境
    uri = 'http://139.224.13.75:18080'; //139.224.13.75 58.34.246.29
  return uri
}


// create an axios instance
const service = axios.create({
  baseURL: getApiUrl(), // api 的 base_url  getApiUrl()  process.env.BASE_API
  timeout: 10000, // request timeout
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
})


// request interceptor
service.interceptors.request.use(
  config => {
    function makeFormData(params) {
      const formData = new FormData();
      Object.keys(params).forEach(key => {
        if (typeof params[key] == "string") {
          formData.append(key, params[key]);
        } else {
          formData.append(key, JSON.stringify(params[key]));
        }
      });
      return formData;
    }
    config.data = makeFormData(config.data); // 调用此方法
    if (store.getters.token) {
      // 让每个请求携带token-- ['Authorization']为自定义key 请根据实际情况自行修改
      config.headers['Authorization'] = getToken()
    }
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    console.log('response code : ' + res.code)// for debug
    var errormsg
    if (res.code === 401) {
      errormsg = '系统未登录，请重新登录'
      // MessageBox.alert(errormsg, '错误', {
      //   confirmButtonText: '确定',
      //   type: 'error'
      // }).then(() => {
      //   store.dispatch('FedLogOut').then(() => {
      //     location.reload()
      //   })
      // })
      return Promise.reject(errormsg)
    } else if (res.code === 403) {
      errormsg = '没有操作权限,请联系管理员授权,或者重新登入'
      MessageBox.alert(errormsg, '错误', {
        confirmButtonText: '确定',
        type: 'error'
      })
      return Promise.reject(errormsg)
    } else if (res.code === 404) {
      errormsg = res.msg + '，' + res.data
      MessageBox.alert(errormsg, '错误', {
        confirmButtonText: '确定',
        type: 'error'
      })
      return Promise.reject(errormsg)
    } else if (res.code === 500) {
      errormsg = '服务器失败，' + res.msg
      MessageBox.alert('服务器失败，' + res.msg, '警告', {
        confirmButtonText: '确定',
        type: 'error'
      })
      return Promise.reject(errormsg)
    } else if (res.code === 500) {
      errormsg = '操作失败，' + res.msg
      MessageBox.alert('操作失败，' + res.msg, '错误', {
        confirmButtonText: '确定',
        type: 'error'
      })
      return Promise.reject(errormsg)
    } else if (res.code === 503) {
      errormsg = '请求业务目前未支持'
      MessageBox.alert('请求业务目前未支持', '警告', {
        confirmButtonText: '确定',
        type: 'error'
      })
      return Promise.reject(errormsg)
    } else if (res.code === 504) {
      errormsg = '更新数据已经失效，请刷新页面重新操作'
      MessageBox.alert('更新数据已经失效，请刷新页面重新操作', '警告', {
        confirmButtonText: '确定',
        type: 'error'
      })
      return Promise.reject(errormsg)
    } else if (res.code === 505) {
      errormsg = '更新失败，请再尝试一次'
      MessageBox.alert('更新失败，请再尝试一次', '警告', {
        confirmButtonText: '确定',
        type: 'error'
      })
      return Promise.reject(errormsg)
    } else if (res.code !== 0 && res.code !== 200) {
      // 非5xx的错误属于业务错误，留给具体页面处理
      return Promise.reject(response)
    } else {
      console.log('request success')// for debug
      return response
    }
  }, error => {
    console.log('err' + error)// for debug
    const errormsg = '登录连接超时（后台不能连接，请联系系统管理员）'
    Message({
      message: errormsg,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(errormsg)
  })

export default service
